package com.mk.legoscans2.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.mk.legoscans2.LegoScans3Application;
import com.mk.legoscans2.R;
import com.mk.legoscans2.Scan;
import com.mk.legoscans2.ScanListAdapter;

public class ScanListFragment extends ListFragment {
	
	String _account;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		_account = LegoScans3Application.AccountService.getAccount();
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		LegoScans3Application.CurrentScan = LegoScans3Application.TempScans.get(position);
		
		if(LegoScans3Application.CurrentScan != null)
		{
			Intent scanIntent = new Intent(getActivity(), ViewScanActivity.class);
			startActivity(scanIntent);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.scans_list, null);
	}
	
	public void updateList()
	{
		FragmentActivity activity = getActivity();
		if(activity != null)
		{
			setIsLoading(false);
			List<Scan> scans = LegoScans3Application.TempScans != null ? LegoScans3Application.TempScans : new ArrayList<Scan>();
			setListAdapter(new ScanListAdapter(activity, scans, _account));
		}
	}
	
	public void setIsLoading(boolean isLoading)
	{
		FragmentActivity activity = getActivity();
		if(activity != null)
		{
			View scansListProgressBar = activity.findViewById(R.id.scansListProgressBar);
			if(scansListProgressBar != null)
				scansListProgressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
			
			getListView().setVisibility(isLoading ? View.GONE : View.VISIBLE);
		}
	}
	
	@Override
	public void onResume() {
		if(LegoScans3Application.UpdateScansList && LegoScans3Application.TempScans != null)
		{
			setListAdapter(new ScanListAdapter(getActivity(), LegoScans3Application.TempScans, _account));
			LegoScans3Application.UpdateScansList = false;
		}
		super.onResume();
	}
	
	public void setAccount(String account) {
		_account = account;
	}
}
